package com.eascs.brand.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.loanapplyoplog.LoanapplyOpLog;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.admin.o2o.loan.dao.LoanapplyOpLogDao;
import com.eascs.app.dao.PageResult;
import com.eascs.app.dao.SqlPageQuery;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.brand.dao.O2oBrandDao;
import com.eascs.brand.dao.O2oPartnerDao;
import com.eascs.brand.entity.O2oPartnerEntity;
import com.eascs.brand.form.O2oBranPage;
import com.eascs.common.util.StringUtil;
import com.eascs.file.FileTypeConstants;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.entity.sys.ActOrgEntity;
import com.eascs.workflow.common.entity.wf.ProcessTemplate;
import com.eascs.workflow.common.service.sequence.SequenceService;
import com.eascs.workflow.common.service.sys.SysOrgService;
import com.eascs.workflow.common.service.wf.WorkFlowService;
import com.eascs.workflow.common.vo.ModelResult;
import com.eascs.workflow.common.vo.WFRequestParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class O2oPartnerService {
	protected final Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	O2oBrandDao brandDao;

	@Autowired
	O2oPartnerDao o2oPartnerDao;

	@Autowired
	LoanapplyOpLogDao loanapplyOpLogDao;

	@Reference
	SequenceService sequenceService;

	@Reference
	WorkFlowService workFlowService;

	@Reference
	SysOrgService sysOrgService;
	
	
	public List<O2oPartnerEntity> getEntityList() {
		String sql = "SELECT * FROM O2O_PARTNER_INFO";
		return brandDao.findEntitys(sql, O2oPartnerEntity.class, new Object[]{});
	}

	public PageResult<Object[]> getPageEntity(O2oBranPage branForm) {
		return o2oPartnerDao.queryPartnerEntityByPage(branForm);
	}

	public O2oPartnerEntity getEntityById(String id) {
		return brandDao.getById(O2oPartnerEntity.class, id);
	}

	public List<O2oPartnerEntity> getEntityByBrandId(String brandId) {
		String sql = "SELECT * FROM O2O_PARTNER_INFO WHERE BRAND_ID=?";
		return brandDao.findEntitys(sql, O2oPartnerEntity.class, brandId);
	}

	@Transactional(transactionManager = "o2oTransactionManager")
	public int deleteById(String id) {
		return brandDao.deleteById(O2oPartnerEntity.class, id);
	}

	/**
	 * @Description:
	 * 				<p>
	 *               根据渠道名称或合作方code查询是否有重复的名称或code
	 *               </p>
	 * @author CXW
	 * @date 2016年11月16日 下午2:59:47
	 * @version V1.0
	 */
	public int checkNameAndCode(String brandName, String brandCode) {
		String sql = "";
		if (!StringUtil.isEmpty(brandName)) {
			sql = "select count(*) from o2o_partner_info where partner_name = ? ";
			return brandDao.findInteger(sql, brandName);
		}
		if (!StringUtil.isEmpty(brandCode)) {
			sql = "select count(*) from o2o_partner_info where partner_code = ?";
			return brandDao.findInteger(sql, brandCode);
		}
		return -1;
	}

	/**
	 * @Description:
	 * 				<p>
	 *               修改记录日志
	 *               </p>
	 * @author CXW
	 * @date 2016年11月18日 上午9:57:10
	 * @version V1.0
	 */
	@Transactional(transactionManager = "o2oTransactionManager")
	public int saveEntityLog(LoanapplyOpLog loanEntity) {
		return loanapplyOpLogDao.insert(loanEntity);
	}

	/**
	 * @Description:
	 * 				<p>
	 *               根据渠道名称或合作方code查询是否有重复的名称或code
	 *               </p>
	 * @author CXW
	 * @date 2016年11月18日 下午1:58:01
	 * @version V1.0
	 */
	public boolean getEntityByNameAndCode(String partnerName, String partnerCode) {
		SqlPageQuery<O2oPartnerEntity> sqlPageQuery = new SqlPageQuery<>(O2oPartnerEntity.class, 10, 0);
		StringBuffer querySql = new StringBuffer();
		querySql.append("select * from o2o_partner_info where 1=1 ");
		if (!StringUtil.isEmpty(partnerName)) {
			querySql.append(" AND partner_name = ? ");
			sqlPageQuery.addParam(partnerName);
		}
		if (!StringUtil.isEmpty(partnerCode)) {
			querySql.append(" AND partner_code = ? ");
			sqlPageQuery.addParam(partnerCode);
		}
		querySql.append(" AND status = 1 ");
		sqlPageQuery.setQuerySql(querySql.toString());
		PageResult<O2oPartnerEntity> findDataWithPage = brandDao.findDataWithPage(sqlPageQuery);

		int size = findDataWithPage.getData().size();
		if (size == 0) {
			return true;
		}
		return false;
	}

	/**
	 * @Description:
	 * 				<p>
	 *               根据渠道名称联想合作方信息
	 *               </p>
	 * @author CXW
	 * @date 2016年11月21日 下午4:26:28
	 * @version V1.0
	 */
	public List<Object[]> getPartnerByName(String name) {
		User user = UserHolder.getUser();
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT OPI.ID,CONCAT(OPI.PARTNER_NAME,'-',OBI.BRAND_NAME) ");
		sql.append(" AS PARTNER_NAME FROM O2O_PARTNER_INFO ");
		sql.append("OPI JOIN O2O_BRAND_INFO OBI ON OBI.ID = OPI.BRAND_ID WHERE ");
		sql.append("(OPI.status = 1 OR OPI.status IS NULL ) AND (OPI.wf_status IN (0,9) OR OPI.wf_status IS NULL)  ");
		ModelResult<List<ActOrgEntity>> s = sysOrgService.getProvinceWithUser(user.getNo());
		List<ActOrgEntity> s1 = s.getModel();
		ActOrgEntity actOrgEntity = null;
		StringBuffer orgIds = new StringBuffer();
		orgIds.append("'1',");
		for (int i = 0; i < s1.size(); i++) {
			actOrgEntity = s1.get(i);
			orgIds.append("'" + actOrgEntity.getOrgId() + "',");
		}
		String orgIds_ = orgIds.substring(0, orgIds.length() - 1);
		sql.append(" and OPI.org_province_id in (" + orgIds_ + ") ");
		sql.append("AND OPI.PARTNER_NAME LIKE ? ");
		
		sql.append(" UNION SELECT OPI.ID,CONCAT(OPI.BUSINESS_LICENSE_NAME,'-',OBI.BRAND_NAME) ");
		sql.append(" AS PARTNER_NAME FROM O2O_DEALER_PARTNER_INFO OPI JOIN O2O_BRAND_INFO OBI ");
		sql.append(" ON OBI.ID = OPI.BRAND_ID WHERE (OPI.STATUS = 1 OR OPI.STATUS IS NULL ) ");
		sql.append(" AND (OPI.WF_STATUS IN (0,9) OR OPI.WF_STATUS IS NULL) ");
		sql.append(" AND OPI.ORG_PROVINCE_ID IN ( " + orgIds_ + ") ");
		sql.append(" AND OPI.BUSINESS_LICENSE_NAME LIKE ? ");
		return brandDao.findObjectsList(sql.toString(), "%" + name + "%", "%" + name + "%");
	}

	/**
	 * @Description:
	 * 				<p>
	 *               根据渠道名称联想佣金推荐方(合作方)
	 *               </p>
	 * @author CXW
	 * @date 2016年11月21日 下午4:26:28
	 * @version V1.0
	 */
	public List<Object[]> getPartnerName(String name) {
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT t.ID,t.PARTNER_NAME from (SELECT opi.id,concat(");
		sql.append("opi.partner_code,'-',opi.partner_name) as PARTNER_NAME FROM o2o_partner_info opi");
		sql.append(" UNION SELECT '24793','S01163-O2O金融' ) t WHERE t.PARTNER_NAME LIKE ? LIMIT 0,10");
		return brandDao.findObjectsList(sql.toString(), "%" + name + "%");
	}

	/**
	 * @Description:
	 * 				<p>
	 *               根据合作方id查询品牌名称
	 *               </p>
	 * @author CXW
	 * @date 2016年11月22日 上午9:25:36
	 * @version V1.0
	 */
	public String getPartnerBrandName(String partnerId) {
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT CONCAT(OPI.PARTNER_CODE,' ',OPI.PARTNER_NAME,'-',");
		sql.append("OBI.BRAND_CODE,' ',OBI.BRAND_NAME) AS PARTNER_NAME FROM ");
		sql.append("O2O_PARTNER_INFO OPI JOIN O2O_BRAND_INFO OBI ON OBI.ID = OPI.BRAND_ID WHERE OPI.ID=?");
		return brandDao.findString(sql.toString(), partnerId);
	}

	public ModelResult<Boolean> insert(O2oPartnerEntity entity) {
		ModelResult<Boolean> modelResult = new ModelResult<>();
		if (entity == null) {
			modelResult.withError("insert.error", "O2oPartnerService insert is null");
		}

		String partnerCode = sequenceService.getSeq("O2O_PARTNER_NO", 5, "HZF");
		entity.setPartnerCode(partnerCode);
		boolean model = o2oPartnerDao.insert(entity);
		modelResult.withModel(model);
		return modelResult;
	}

	public ModelResult<Boolean> delete(String partnerId) {
		ModelResult<Boolean> modelResult = new ModelResult<>();
		if (StringUtils.isBlank(partnerId)) {
			modelResult.withError("delete.error", "O2oPartnerService delete is null");
		}

		boolean model = o2oPartnerDao.delete(partnerId);
		modelResult.withModel(model);
		return modelResult;
	}

	public ModelResult<Boolean> update(O2oPartnerEntity entity) {
		ModelResult<Boolean> modelResult = new ModelResult<>();
		if (entity == null) {
			modelResult.withError("update.error", "O2oPartnerService update is null");
		}

		String partnerId = entity.getId();
		if (StringUtils.isBlank(partnerId)) {
			modelResult.withError("update.error", "O2oPartnerService update is null");
		}

		/** 对象update操作时，防止为传入null数据替换状态、时间等数据 */
		O2oPartnerEntity pe = o2oPartnerDao.queryPartnerEntityById(partnerId);
		if (pe == null) {
			modelResult.withError("update.error", "O2oPartnerService update is null");
		}
		entity.setPartnerCode(pe.getPartnerCode());
		entity.setCreateTime(pe.getCreateTime());
		entity.setWfStatus(pe.getWfStatus());
		entity.setStatus(pe.getStatus());

		boolean model = o2oPartnerDao.update(entity);
		modelResult.withModel(model);
		return modelResult;
	}

	public ModelResult<O2oPartnerEntity> queryPartnerEntityById(String partnerId) {
		ModelResult<O2oPartnerEntity> modelResult = new ModelResult<>();
		if (StringUtils.isBlank(partnerId)) {
			modelResult.withError("query.error", "O2oPartnerService queryPartnerEntityById partnerId is null");
		}

		O2oPartnerEntity model = o2oPartnerDao.queryPartnerEntityById(partnerId);
		modelResult.withModel(model);
		return modelResult;
	}

	public ModelResult<PageResult<Object[]>> queryPartnerEntityByPage(O2oBranPage branForm) {
		ModelResult<PageResult<Object[]>> modelResult = new ModelResult<>();
		if (branForm == null) {
			modelResult.withError("query.error", "O2oPartnerService queryPartnerEntityByPage branForm is null");
		}

		PageResult<Object[]> model = o2oPartnerDao.queryPartnerEntityByPage(branForm);
		modelResult.withModel(model);
		return modelResult;
	}

	public ModelResult<List<Object[]>> queryPartnerAllLikeName(String partnerName) {
		ModelResult<List<Object[]>> modelResult = new ModelResult<>();
		if (StringUtils.isBlank(partnerName)) {
			modelResult.withError("query.error", "O2oPartnerService queryPartnerAllLikeName partnerName is null");
		}

		List<Object[]> model = o2oPartnerDao.queryPartnerAllLikeName(partnerName);
		modelResult.withModel(model);
		return modelResult;
	}

	/**
	 * @Title: startUp
	 * @Description: 启动合作方申请
	 * @author
	 * @param partnerNo
	 * @return
	 * @return ModelResult<Boolean>
	 * @throws @date
	 *             2017年3月16日 上午10:03:48
	 */
	public ModelResult<Boolean> startUp(String partnerNo) {
		try {
			O2oPartnerEntity partner = o2oPartnerDao.queryPartnerEntityById(partnerNo);
			WFRequestParam param = new WFRequestParam();
			param.setReferId(partnerNo);
			param.setReferCode(partner.getPartnerCode());
			param.setReferUrl("/rpartner/view_flow");
			param.setSystemModule(ProcessTemplate.SYSTEM_MODULE_O2O);
			param.setProcessType(String.valueOf(ProcessTemplate.PROECESS_TYPE_PARTNERS_AUDIT_BP));
			param.setProcessVersion("v1");
			User user = UserHolder.getUser();
			param.setAppliedby(user.getNo());
			param.setAppliedbyName(user.getCname());
			param.setOrgNo(partner.getOrgId());
			param.setAppliedDes("渠道名称：" + partner.getPartnerName() + ", 经办人：" + user.getCname());

			/*if(StringUtil.isNotBlank(user.getOrg()) && user.getOrg().equals("1")) {
				List<String> list = new ArrayList<>();
				list.add("ppdsp");
				param.setExcludeNodeCodeList(list);
			}*/
			logger.info("启动合作方申请，参数有合作方id：【{}】，合作方编号：【{}】，系统模块：【{}】，流程类型：【{}】，经营平台id：【{}】", partnerNo, partner.getPartnerCode(), ProcessTemplate.SYSTEM_MODULE_O2O, param.getProcessType(), partner.getOrgId());
			ModelResult<Boolean> modelResult = workFlowService.instance(param);
			if (modelResult.isSuccess() && modelResult.getModel()) {
				o2oPartnerDao.processPartnerStart(partnerNo);
			} else {
				logger.error("启动合作方申请失败，合作方id：【{}】，错误信息{}", partnerNo, modelResult.getErrMsg());
			}
			return modelResult;
		} catch (Exception e) {
			logger.error("启动合作方申请失败，合作方id：【{}】，错误：{}，", partnerNo, e.getMessage());
			return new ModelResult<Boolean>("partner error", "启动合作方申请失败");
		}
	}

	/**
	 * @Description:
	 * 				<p>
	 *               根据查询合作方name或者品牌name查询合作方id
	 *               </p>
	 * @author CXW
	 * @date 2017年2月16日 上午10:40:13
	 * @version V1.0
	 */
	public List<Object[]> getPartnerIds(String partnerName, String brandName) {
		List<Object[]> data = new ArrayList<>();
		if (!StringUtils.isEmpty(partnerName)) {
			data = o2oPartnerDao.getPartnerIdsByName(partnerName);
		}
		if (!StringUtils.isEmpty(brandName)) {
			data = o2oPartnerDao.getPartnerIdsByBrandName(brandName);
		}
		if (!StringUtils.isEmpty(partnerName) && !StringUtils.isEmpty(brandName)) {
			data = o2oPartnerDao.getPartnerIds(partnerName, brandName);
		}
		return data;
	}

	public ModelResult<Boolean> checkAttachment(String id) {
		ModelResult<Boolean> modelResult = new ModelResult<>();
		String sql = "select d.datalist_code from o2o_datalist d where d.is_delete=? and d.loanapply_no=?";
		List<String> code = o2oPartnerDao.findSimpleObjectList(sql, String.class, StatusContexts.O2O_NO, id);

		if (code != null && code.size() > 0) {
			if (!code.contains(FileTypeConstants.PARTNER_TYPE_RPMENT)) {
				modelResult.setModel(false);
				modelResult.setErrMsg("请上传合作方申请报告");
			} else if (!code.contains(FileTypeConstants.PARTNER_TYPE_PICTURE)) {
				modelResult.setModel(false);
				modelResult.setErrMsg("请上传上门营销照片");
			} else if (!code.contains(FileTypeConstants.PARTNER_TYPE_EVIDENCE)) {
				modelResult.setModel(false);
				modelResult.setErrMsg("请上传厂家证明文件");
			} else {
				modelResult.setModel(true);
			}
		} else {
			modelResult.setModel(false);
			modelResult.setErrMsg("请上传附件");
		}
		return modelResult;

	}

	public ModelResult<Boolean> checkJxsAttachment(String id) {
		ModelResult<Boolean> modelResult = new ModelResult<>();
		String sql = "select d.datalist_code from o2o_datalist d where d.is_delete=? and d.loanapply_no=?";
		List<String> code = o2oPartnerDao.findSimpleObjectList(sql, String.class, StatusContexts.O2O_NO, id);

		if (code != null && code.size() > 0) {
			if (!code.contains(FileTypeConstants.JXS_PARTNER_TYPE_RPMENT)) {
				modelResult.setModel(false);
				modelResult.setErrMsg("请上传合作方申请报告");
			} else if (!code.contains(FileTypeConstants.JXS_PARTNER_TYPE_PICTURE)) {
				modelResult.setModel(false);
				modelResult.setErrMsg("请上传上门营销照片");
			} else if (!code.contains(FileTypeConstants.JXS_PARTNER_TYPE_EVIDENCE)) {
				modelResult.setModel(false);
				modelResult.setErrMsg("请上传厂家证明文件");
			} else {
				modelResult.setModel(true);
			}
		} else {
			modelResult.setModel(false);
			modelResult.setErrMsg("请上传附件");
		}
		return modelResult;

	}

}
